package com.dkd.common.test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class AopProxyExample {

    public static void main(String[] args) {
        //目标对象
        MyService target = new MyServiceImpl();
        //调用处理器
        MyInvocationHandler myInvocationHandler = new MyInvocationHandler(target);
        //创建动态代理对象
        MyService myService = (MyService) Proxy.newProxyInstance(MyService.class.getClassLoader(),
                new Class<?>[]{MyService.class}, myInvocationHandler);
        //调用代理对象的方法
        myService.doSomething();
    }

}

//定义一个接口
interface MyService {
    void doSomething();
}

//实现接口的目标对象
class MyServiceImpl implements MyService {
    @Override
    public void doSomething() {
        System.out.println("Doing something...");
    }
}

//定义一个调用处理器
class MyInvocationHandler implements InvocationHandler {

    private final Object target;

    public MyInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Before method call: " + method.getName());
        Object result = method.invoke(target, args); // 调用目标方法
        System.out.println("After method call: " + method.getName());
        return result;
    }
}